﻿package com.bizmlib.utils
{

	public class DateUtil
	{
		public static var monthsDays:Array = [31,28,31,30,31,30,31,31,30,31,30,31];
		
		
		public static function rangeToDays(fromDate:Date, toDate:Date, returnNegative:Boolean=false, includeEndDate:Boolean=false):int
		{
			var dateA:Date = new Date(Math.min(fromDate.time, toDate.time));
			var dateB:Date = new Date(Math.max(fromDate.time, toDate.time));
			var dateANumber:int = dayNumber(dateA);
			var dateBNumber:int = dayNumber(dateB);
			var result:int = dateBNumber - dateANumber;
			
			while(dateA.fullYear<dateB.fullYear)
			{
				result += daysInYear(dateA.fullYear++);
			}
			
			result += Number(includeEndDate);
			
			if(returnNegative && fromDate.time>toDate.time)
				result *= -1;
			
			return result;
		}
		
		public static function dayNumber(date:Date):int
		{
			var number:int = 0;
			for(var i:int=0; i<date.month; i++)
			{
				number += daysInMonth(i);
			}
			number += date.date;
			return number;
		}
		public static function isLeapYear(year:Number):Boolean
		{
			return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
		}
		public static function daysInMonth(month:int, year:Number = undefined):int
		{
			if (month==1 && (!isNaN(year) && isLeapYear(year)))
			{
				return 29;
			}
		
			return monthsDays[month];
		
		}
		public static function daysInYear(year:Number):int
		{
			return isLeapYear(year) ? 366 : 365;
		}
	}
}